package controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import pagemodel.RegisterUser;
import pagemodel.User;
import po.Customer;
import po.Staff;
import service.LoginService;
import web.CaptchaUtil;
import pagemodel.MSG;

@Controller
public class Login {
	@Autowired
	LoginService loginservice;
	
	@RequestMapping(value="/loginvalidate",method = RequestMethod.POST)
	@ResponseBody
	public MSG loginvalidate(@RequestBody User u,HttpSession httpSession){
		String picode=(String) httpSession.getAttribute("rand");
		System.out.println("传过来的picode："+u.getPic());
		System.out.println("后台生成picode:"+picode);
		if(!picode.equalsIgnoreCase(u.getPic()))
			return new MSG("error code");
		if(u.getUsername()==null)
			return new MSG("username is null");
		String realpwd=loginservice.getpwdbyname(u.getUsername());
		if(realpwd!=null&&realpwd.equals(u.getPassword()))
		{
			httpSession.setAttribute("username", u.getUsername());
			return new MSG("success");
		}else
			return new MSG("error password");
	}
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String login(){
		return "/html/login.html";
	}
	
	@RequestMapping(value="/logout",method = RequestMethod.GET)
	public String logout(HttpSession httpSession){
		httpSession.removeAttribute("username");
		return "/html/login.html";
	}
	
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
    @ResponseBody
    public void captcha(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        CaptchaUtil.outputCaptcha(request, response);
    }
	
	@RequestMapping(value="/current",method = RequestMethod.GET)
	@ResponseBody
	public MSG currentuser(HttpSession httpSession){
		String username=(String)httpSession.getAttribute("username");
		return new MSG(username);
	}


	@RequestMapping(value = "/checkUser",method = RequestMethod.POST)
	@ResponseBody
	public MSG checkUser(@RequestParam("username")String username){
		String pwd =loginservice.getpwdbyname(username);
		if (pwd!=null){
			MSG msg = new MSG("100","用户名别人抢先注册了！换一个吧！");
			return  msg;
		}
		return new MSG("200");
	}	//mother fucker  f

	/*  JSR303 BindingResult 对象必须在 @Valid 的紧挨着的后面，否则接收不到错误信息。 */
	@RequestMapping(value = "/register",method = RequestMethod.POST)//
	@ResponseBody
	public MSG registerUser(@Valid @RequestBody  RegisterUser registerUser, BindingResult result , HttpSession httpSession){
		String picode=(String) httpSession.getAttribute("rand");
		if (result.hasErrors()){//校验失败
			FieldError fieldError= result.getFieldError();
			if (fieldError.getField().equals("regisUsername")){
			return  new MSG("100","username",fieldError.getDefaultMessage());
			}if (fieldError.getField().equals("regisPassword")){
				return  new MSG("100","password",fieldError.getDefaultMessage());
			}
		}
		if(!picode.equalsIgnoreCase(registerUser.getRegis_pic())){
			return  new MSG("100","验证码错误！");
		}

		Staff staff = new Staff();
		registerUser.toString();
		staff.setUsername(registerUser.getRegisUsername());
		staff.setPassword(registerUser.getRegisPassword());
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-mm-dd");
		Date date = new Date();
		System.out.println(date.toString());
		staff.setCreate_time(dateformat.format(date));
		loginservice.registerUser(staff);
		return new MSG("200",registerUser.getRegisUsername());
	}


	@ApiOperation("会员注册")
	@RequestMapping(value = "/registerc",method = RequestMethod.POST)//
	public MSG Registercustomer(@RequestBody RegisterUser registerUser,HttpSession httpSession){
		String picode=(String) httpSession.getAttribute("rand");
		if(!picode.equalsIgnoreCase(registerUser.getRegis_pic())){
			return  new MSG("100","验证码错误！");
		}
		Customer customer = new Customer();
		customer.setUsername(registerUser.getRegisUsername());
		customer.setPassword(registerUser.getRegisPassword());
		loginservice.registerCustomer(customer);
		return  new MSG("200");
	}


	@RequestMapping("/loginCustomer")
	@ResponseBody
	public MSG loginCustomer(@RequestBody Customer customer){
		String pwd = loginservice.getpwdByCustomerName(customer.getUsername());
		return  null;
	}

  }
